﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using log4net;
using System.ServiceModel.Description;

namespace HgRemoteServer
{
	public class OperationLogger : IParameterInspector
	{
		public ILog Log = LogManager.GetLogger(typeof(OperationLogger));

		public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
		{
			Log.InfoFormat("Operation {0} complete.", operationName);
		}

		public object BeforeCall(string operationName, object[] inputs)
		{
			Log.InfoFormat("Operation {0} starting.", operationName);
			return null;
		}
	}

	public class LoggerBehavior : IServiceBehavior
	{
		public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
		{
		}

		public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
		{
			OperationLogger logger = new OperationLogger();
			foreach(ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
			{
				foreach(EndpointDispatcher ed in dispatcher.Endpoints)
				{
					foreach (var op in ed.DispatchRuntime.Operations)
					{
						op.ParameterInspectors.Add(logger);
					}
				}
			}
		}

		public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
		{
		}

	}
}
